<template>
  <div>
    <div class="ml-2 flex-1">
      <div>
        <a-card :bordered="false" style="height: 830px; width: 1380px">
          <a-form :model="searchForm" layout="inline" class="mt-3" ref="searchFormRef">
            <a-form-item label="归属机构" name="comId">
              <!-- <a-tree-select
                v-model:value="searchForm.comId"
                style="width: 320px"
                :tree-data="comanyList"
                allow-clear
                placeholder="请选择归属机构"
                tree-node-filter-prop="label"
                :load-data="onLoadDatas"
                tree-checkable
              /> -->
              <a-tree-select v-model:value="searchForm.comId" tree-node-filter-prop="label" style="width: 260px"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" :tree-data="comanyList"
                placeholder="请选择归属机构" />
            </a-form-item>
            <a-form-item label="收费期" name="feeDate">
              <a-date-picker v-model:value="searchForm.feeDate" picker="year" />
            </a-form-item>
            <a-form-item label="业务类型" name="grState">
              <a-select v-model:value="searchForm.grState" placeholder="请选择" style="width: 200px">
                <a-select-option value="1">增值税普通发票</a-select-option>
                <a-select-option value="2">增值税专用发票</a-select-option>
                <a-select-option value="3">增值税电子发票</a-select-option>
                <a-select-option value="4">普通发票</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="收费时间" name="time">
              <a-range-picker v-model:value="searchForm.time" />
            </a-form-item>
            <a-form-item>
              <a-button type="primary" class="mr-3" :icon="h(SearchOutlined)" @click="onSearch">查询</a-button>
              <a-button type="primary" :icon="h(RedoOutlined)" class="mr-3" @click="onReset">重置</a-button>
              <a-button type="primary" :icon="h(HistoryOutlined)" class="mr-3" @click="onHistory">导出历史</a-button>
              <a-button type="primary" :icon="h(ReconciliationOutlined)" class="mr-3" @click="onExport">导出信息</a-button>
            </a-form-item>
          </a-form>
          <a-table :columns="columns" :data-source="dataSource" bordered :pagination="pagination" class="mt-5"
            :row-class-name="(_record: any, index: number) =>
              index % 2 === 1 ? 'table-striped' : null
              " :scroll="{ x: 4500, y: 550 }">
          </a-table>
        </a-card>
      </div>
    </div>
    <a-modal title="导出历史" :visible="showHistory" @cancel="onCancel" width="1400px">
      <a-table :columns="historyColumns" :data-source="historyDataSource" bordered :pagination="historyPagination"
        class="mt-5" :row-class-name="(_record: any, index: number) =>
          index % 2 === 1 ? 'table-striped' : null
          ">
        <template #bodyCell="{ column, record, text }">
          <template v-if="column.dataIndex === 'states'">
            <a-tag :bordered="false" color="success" v-if="record.states == '0'">完成</a-tag>
            <a-tag :bordered="false" color="error" v-else>失败</a-tag>
          </template>
          <template v-if="column.dataIndex === 'active'">
            <a-button type="link" @click="onDown(record)">下载</a-button>
          </template>
        </template>
      </a-table>
    </a-modal>
  </div>
</template>
<script lang="ts" setup>
import { ref, reactive, h } from 'vue';
import {
  SearchOutlined,
  RedoOutlined,
  HistoryOutlined,
  ReconciliationOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import {
  getUserChargeDetailApi,
  getChargeUserExportApi,
  getReportExportHistoryApi,
} from '#/api/core/statistical';
import { getCompanyTree } from '#/api/core/develop';
import { getAllTree } from '#/api/core/customerInformation';
import dayjs from 'dayjs';
const props = defineProps({
  selectedNodeId: {
    type: Array,
    default: [],
  },
});
const searchFormRef = ref(null);
const searchForm = reactive({
  time: '',
  comId: undefined,
  feeDate: '',
  grState: undefined,
});
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const historyPagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    historyPagination.current = page;
    historyPagination.pageSize = pageSize;
    onHistory();
  },
});
const showHistory = ref(false);
const historyDataSource = ref([]);
const dataSource = ref([]);
const comanyList = ref([]);
// const getComany = () => {
//   getAllTree(1, "").then((res: any) => {
//     console.log(res);
//     // 递归处理树形数据，保持层级结构
//     const processTreeData = (tree: any[]): any[] => {
//       return tree.map((item: any) => {
//         console.log(item);
//         const processedItem = {
//           key: item.id,
//           label: item.title,
//           level: item.level,
//           value: item.id,
//           isLeaf: item.level !== 5 ? false : true,
//         };

//         // 如果存在children，递归处理子节点
//         if (item.children && item.children.length > 0) {
//           processedItem.children = processTreeData(item.children);
//         }

//         return processedItem;
//       });
//     };

//     const treeData = processTreeData(res);
//     comanyList.value = treeData;
//     console.log(treeData);
//   });
// };
// getComany();
const getTableData = () => {
  getCompanyTree().then((res: any) => {
    // console.log(res);
    // 递归处理树形数据，保持层级结构
    const processTreeData = (tree: any[]): any[] => {
      console.log(tree);
      return tree.map((item: any) => {
        const processedItem = {
          key: item.id,
          label: item.name,
          value: item.id,
          isLeaf: item.children && item.children.length > 0 ? false : true,
          children: [],
        };

        // 如果存在children，递归处理子节点
        if (item.children && item.children.length > 0) {
          processedItem.children = processTreeData(item.children);
        }

        return processedItem;
      });
    };

    const treeData = processTreeData([res.data]);
    comanyList.value = treeData;
    console.log(comanyList.value);
  });
};
getTableData();
const onLoadDatas = (treeNode: any) => {
  return new Promise((resolve) => {
    console.log(treeNode);
    // 如果是叶子节点，直接返回
    if (treeNode.isLeaf) {
      resolve(undefined);
      return;
    }

    // 加载子节点数据
    getAllTree(1, treeNode.key)
      .then((res: any) => {
        const children = res.map((item: any) => {
          console.log(item);
          return {
            id: item.id ? item.id : item.id,
            value: item.id ? item.id : item.id,
            title: item.title,
            key: item.id ? item.id : item.id,
            isLeaf: item.level !== 5 ? false : true, // 如果有userId说明是叶子节点
          };
        });

        // 找到对应的节点并更新其children
        const updateNode = (nodes: any[]) => {
          console.log(nodes, children);
          for (let node of nodes) {
            if (node.key === treeNode.key) {
              node.children = children;
              return true;
            }
            if (node.children && updateNode(node.children)) {
              return true;
            }
          }
          return false;
        };

        updateNode(comanyList.value);
        comanyList.value = [...comanyList.value];
        console.log(comanyList.value);
        resolve(undefined);
      })
      .catch((error) => {
        console.error('加载子节点失败:', error);
        message.error('加载子节点失败');
        resolve(undefined);
      });
  });
};
const columns = [
  {
    title: '公司名称',
    dataIndex: 'name',
    key: 'name',
    align: 'center',
  },
  {
    title: '换热站名称',
    dataIndex: 'heatExchangeStationName',
    key: 'heatExchangeStationName',
    align: 'center',
  },
  {
    title: '小区',
    dataIndex: 'village',
    key: 'village',
    align: 'center',
  },
  {
    title: '小区编号',
    dataIndex: 'villageCode',
    key: 'villageCode',
    align: 'center',
  },
  {
    title: '住户编号',
    dataIndex: 'alipayConsNo',
    key: 'alipayConsNo',
    align: 'center',
  },
  {
    title: '住户地址',
    dataIndex: 'houseAddress',
    key: 'houseAddress',
    align: 'center',
  },
  {
    title: '用户名称',
    dataIndex: 'holder',
    key: 'holder',
    align: 'center',
  },
  {
    title: '供热面积',
    dataIndex: 'buildingArea',
    key: 'buildingArea',
    align: 'center',
  },
  {
    title: '用户类型',
    dataIndex: 'ywlx',
    key: 'ywlx',
    align: 'center',
  },
  {
    title: '居民/非居民类型',
    dataIndex: 'houseType',
    key: 'houseType',
    align: 'center',
  },
  {
    title: '计量单价',
    dataIndex: 'jldj',
    key: 'jldj',
    align: 'center',
  },
  {
    title: '应收违约金',
    dataIndex: 'yswyj',
    key: 'yswyj',
    align: 'center',
  },
  {
    title: '用户电话',
    dataIndex: 'holdPhone',
    key: 'holdPhone',
    align: 'center',
  },
  {
    title: '生成应收时间',
    dataIndex: 'jfsj',
    key: 'jfsj',
    align: 'center',
  },
  {
    title: '应收计量',
    dataIndex: 'jlysjbf',
    key: 'jlysjbf',
    align: 'center',
  },
  {
    title: '抹零金额',
    dataIndex: 'mlje',
    key: 'mlje',
    align: 'center',
  },
  {
    title: '实收合计',
    dataIndex: 'shhj',
    key: 'shhj',
    align: 'center',
  },
  {
    title: '缴费面积',
    dataIndex: 'feeArea',
    key: 'feeArea',
    align: 'center',
  },
  {
    title: '入网年度',
    dataIndex: 'netDate',
    key: 'netDate',
    align: 'center',
  },
  {
    title: '使用类型',
    dataIndex: 'sylx',
    key: 'sylx',
    align: 'center',
  },
  {
    title: '生成方式',
    dataIndex: 'scfs',
    key: 'scfs',
    align: 'center',
  },
  {
    title: '收费期',
    dataIndex: 'sfq',
    key: 'sfq',
    align: 'center',
  },
  {
    title: '单价',
    dataIndex: 'price',
    key: 'price',
    align: 'center',
  },
  {
    title: '应收全费金额',
    dataIndex: 'ysqfje',
    key: 'ysqfje',
    align: 'center',
  },
  {
    title: '应收基本费金额',
    dataIndex: 'ysjbfje',
    key: 'ysjbfje',
    align: 'center',
  },
  {
    title: '应收减免金额',
    dataIndex: 'ysjmje',
    key: 'ysjmje',
    align: 'center',
  },
  {
    title: '优惠合计',
    dataIndex: 'yhje',
    key: 'yhje',
    align: 'center',
  },
  {
    title: '实收面积',
    dataIndex: 'ssmj',
    key: 'ssmj',
    align: 'center',
  },
];
const historyColumns = [
  {
    title: '文件名',
    dataIndex: 'fileName',
    key: 'fileName',
    align: 'center',
  },
  {
    title: '操作日期',
    dataIndex: 'operationDate',
    key: 'operationDate',
    align: 'center',
  },
  {
    title: '结束时间',
    dataIndex: 'endTime',
    key: 'endTime',
    align: 'center',
  },
  {
    title: '操作人',
    dataIndex: 'operator',
    key: 'operator',
    align: 'center',
  },
  {
    title: '机构',
    dataIndex: 'comName',
    key: 'comName',
    align: 'center',
  },
  {
    title: '状态',
    dataIndex: 'states',
    key: 'states',
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'active',
    key: 'active',
    align: 'center',
  },
];
const onSearch = () => {
  if (!props.selectedNodeId || props.selectedNodeId.length === 0) {
    message.error("请选择左侧树结构！");
    return;
  } else if (!searchForm.time) {
    message.error("请选择收费时间！");
    return;
  } else {
    const query = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      time: searchForm.time ? `${dayjs(searchForm.time[0]).format('YYYY-MM-DD')},${dayjs(
        searchForm.time[1],
      ).format('YYYY-MM-DD')}` : '',
      comId: searchForm.comId ?? '',
      feeDate: searchForm.feeDate ? dayjs(searchForm.feeDate).format('YYYY') : '',
      grState: searchForm.grState ?? '',
      treeData: props.selectedNodeId,
    };
    getUserChargeDetailApi(query).then((res: any) => {
      console.log('用户报表', res);
      if (res) {
        dataSource.value = res.data;
        pagination.total = res.total;
      }
    });
  }

};
const onExport = () => {
  if (!props.selectedNodeId || props.selectedNodeId.length === 0) {
    message.error("请选择左侧树结构！");
    return;
  }
  const query = {
    time: `${dayjs(searchForm.time[0]).format('YYYY-MM-DD')},${dayjs(
      searchForm.time[1],
    ).format('YYYY-MM-DD')}`,
    comId: searchForm.comId ?? '',
    feeDate: searchForm.feeDate ? dayjs(searchForm.feeDate).format('YYYY') : '',
    grState: searchForm.grState ?? '',
    treeData: props.selectedNodeId,
  };
  getChargeUserExportApi(query).then((res: any) => {
    console.log('导出信息', res);
    if (res.data.code === 200) {
      message.success(res.data.msg);
    } else {
      message.error('导出失败');
    }
  });
};
const onHistory = () => {
  showHistory.value = true;
  const query = {
    pageNo: historyPagination.current,
    pageSize: historyPagination.pageSize,
    levels: 2,
  };
  getReportExportHistoryApi(query).then((res: any) => {
    console.log('导出历史', res);
    if (res) {
      historyDataSource.value = res.data;
      historyPagination.total = res.total;
    }
  });
};
const onCancel = () => {
  showHistory.value = false;
};
const onDown = (e: any) => {
  // console.log(e);
  const loading = message.loading({
    content: "下载中...",
    duration: 0,
  });

  try {
    // 下载地址拼接
    const url = e.urlAddress;

    // 使用a标签下载，避免X-Frame-Options错误
    const link = document.createElement("a");
    link.href = url;
    link.download = ""; // 触发下载而不是导航
    link.target = "_blank";
    link.style.display = "none";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);

    // 关闭loading
    setTimeout(() => {
      loading();
    }, 1000);
  } catch (error) {
    console.error("下载出错:", error);
    message.error("下载出错，请重试");
    loading();
  }
};
const onReset = () => {
  searchFormRef.value.resetFields();
};
</script>
<style scoped>
:deep(.ant-form-item) {
  margin-bottom: 10px !important;
}
</style>
